package com.huijiet.ueditor.upload;


import com.alibaba.fastjson.JSON;
import com.huijiet.ueditor.PathFormat;
import com.huijiet.ueditor.define.AppInfo;
import com.huijiet.ueditor.define.BaseState;
import com.huijiet.ueditor.define.FileType;
import com.huijiet.ueditor.define.State;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
import java.util.Map;


public class BinaryUploader {

	public static final State save(HttpServletRequest request,
								   Map<String, Object> conf) {

		if(!(request instanceof MultipartHttpServletRequest)){
			System.out.println("不是文件上传");
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}
		MultipartHttpServletRequest mrequest = (MultipartHttpServletRequest) request;
		Enumeration<String> parameterNames = mrequest.getParameterNames();
		while (parameterNames.hasMoreElements()){
			String name = parameterNames.nextElement();
			System.out.println(name);
		}
		System.out.println(JSON.toJSONString(conf));

		Map<String, MultipartFile> fileMap = mrequest.getFileMap();
		MultipartFile file = null;
		String originFileName = null;
		long size = 0;

		for(Map.Entry<String,MultipartFile> entry : fileMap.entrySet()){
			String name = entry.getKey();
			file = entry.getValue();
			originFileName = file.getOriginalFilename();
			size = file.getSize();
			System.out.println("name:"+name);
			System.out.println("originalFilename:"+originFileName);
			System.out.println("size:"+size);
		}
		String savePath = (String) conf.get("savePath");
		String suffix = FileType.getSuffixByFilename(originFileName);
		originFileName = originFileName.substring(0,
				originFileName.length() - suffix.length());
		savePath = savePath + suffix;
		long maxSize = ((Long) conf.get("maxSize")).longValue();
		if(maxSize<=size){
			return new BaseState(false, AppInfo.MAX_SIZE);
		}
		if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
			return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
		}
		savePath = PathFormat.parse(savePath, originFileName);
		String physicalPath = (String) conf.get("rootPath") + savePath;

		try (InputStream is = file.getInputStream()){
			State storageState = StorageManager.saveFileByInputStream(is,
					physicalPath, maxSize);
			if (storageState.isSuccess()) {
				storageState.putInfo("url", PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}
			return storageState;

		} catch (IOException e) {
			e.printStackTrace();
		}
		return new BaseState(false, AppInfo.IO_ERROR);



	}

	private static boolean validType(String type, String[] allowTypes) {
		List<String> list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}
